package mil.af.amc.adpetracker.web.actions.ItemModel;

import mil.af.amc.adpetracker.model.ItemModel;
import mil.af.amc.adpetracker.service.ItemModelService;
import mil.af.amc.adpetracker.web.actions.AbstractAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class GetItemModelsByEquipmentTypeAction extends AbstractAction {

    private ItemModelService itemModelService;

    public void setItemModelService(ItemModelService itemModelService) {
        this.itemModelService = itemModelService;
    }

//    private EquipmentTypeService equipmentTypeService;
//
//    public void setEquipmentTypeService(EquipmentTypeService equipmentTypeService) {
//        this.equipmentTypeService = equipmentTypeService;
//    }

    @SuppressWarnings({"unchecked"})
    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        Integer equipmentTypeId;

        // KLUDGE ALERT! From now on the interface for my model objects will have "id" and "name", I promise!
        if (httpServletRequest.getParameter("equipmentTypeId") != null) {
            equipmentTypeId = Integer.parseInt(httpServletRequest.getParameter("equipmentTypeId"));
        } else {
            equipmentTypeId = Integer.parseInt(httpServletRequest.getParameter("id"));
        }

        List<ItemModel> results = itemModelService.getByEquipmentType(equipmentTypeId);
        Collections.sort(results);

        JSONArray jsonArray = new JSONArray();
        for(ItemModel model:results) {

            Map jsonMap = new HashMap();
            jsonMap.put("id",model.getModelId());
            jsonMap.put("name", model.getName());

            JSONObject jsonObject = JSONObject.fromObject(jsonMap);
            jsonArray.add(jsonObject);
        }

        httpServletResponse.setHeader("Content-Type", "application/json");
        httpServletResponse.getWriter().println(jsonArray);

        return null;

    }
}
